package com.ae.base.block;

import com.ae.base.ModConstant;
import com.ae.base.PlacedRegister;
import com.ae.base.cap.SingleItemStackHandler;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.state.DirectionProperty;
import net.minecraft.state.EnumProperty;
import net.minecraft.state.IntegerProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraftforge.common.ToolType;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class PlacedItem extends Block {
    public static final IntegerProperty COUNT = IntegerProperty.create("count", 0, 64);
    public static EnumProperty<Direction> DIRECTION = DirectionProperty.create("direction", Direction.EAST, Direction.WEST, Direction.SOUTH, Direction.NORTH, Direction.UP, Direction.DOWN);

    public PlacedItem() {
        super(Properties
                .of(Material.METAL)
                .harvestLevel(4)
                .harvestTool(ToolType.PICKAXE)
                .sound(SoundType.METAL)
                .noOcclusion()
                .strength(3f)
        );
        registerDefaultState(getStateDefinition().any().setValue(COUNT, 1).setValue(DIRECTION, Direction.NORTH));
    }

    @Override
    protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) {
        super.createBlockStateDefinition(builder);
        //自定义的状态添加的方块里
        builder.add(COUNT).add(DIRECTION);
    }

    @Override
    public ActionResultType use(@Nullable BlockState state, World world, @Nonnull BlockPos pos, @Nonnull PlayerEntity player, @Nonnull Hand hand, @Nonnull BlockRayTraceResult ray) {
        //右击时把物品取回
        if (!world.isClientSide && !player.isShiftKeyDown() && hand == Hand.MAIN_HAND) {
            return take(world, pos, player);
        }

        return ActionResultType.PASS;
    }

    private ActionResultType take(World world, BlockPos pos, PlayerEntity player) {
        TileEntity tile = world.getBlockEntity(pos);

        //检测是否为PlacedItemTile。
        if (!(tile instanceof PlacedItemTile)) {
            return ActionResultType.PASS;
        }

        SingleItemStackHandler handler = ((PlacedItemTile) tile).handler;

        if (handler.getStackInSlot().getCount() == handler.getMaxCount()) {
            if (take(world, pos.above(), player) == ActionResultType.SUCCESS) {
                return ActionResultType.SUCCESS;
            }
        }

        ItemStack stack = handler.extractItem(1, false);

        if (stack.isEmpty()) {
            return ActionResultType.PASS;
        }

        if (!player.inventory.add(stack)) {
            InventoryHelper.dropItemStack(world, player.position().x, player.position().y, player.position().z, stack);
        }

        return ActionResultType.SUCCESS;
    }

    @Override
    public boolean hasTileEntity(BlockState state) {
        return true;
    }

    @Nullable
    @Override
    public TileEntity createTileEntity(BlockState state, IBlockReader world) {
        return new PlacedItemTile();
    }

    @Override
    public VoxelShape getShape(BlockState state, @Nonnull IBlockReader reader, @Nonnull BlockPos pos, @Nonnull ISelectionContext context) {
        TileEntity tile = reader.getBlockEntity(pos);
        //从tile内获取shapeId，并从shapeMap里取出shape
        if (tile instanceof PlacedItemTile) {
            return PlacedRegister.placedMap.get(((PlacedItemTile) tile).getId()).getShape(state.getValue(COUNT));
        }else {
            //如果有可能没有tile，则使用默认碰撞箱（正常情况不会出现）
            return PlacedRegister.placedMap.get(ModConstant.ITEM_PLACED).getShape(state.getValue(COUNT));
        }
    }

    @Override
    public void onRemove(BlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos, BlockState newState, boolean isMoving) {
        if (!state.is(newState.getBlock())) {
            TileEntity tile = worldIn.getBlockEntity(pos);
            if (tile instanceof PlacedItemTile) {
                ((PlacedItemTile) tile).dropAll(worldIn, pos, (PlacedItemTile) tile);
            }

            super.onRemove(state, worldIn, pos, newState, isMoving);
        }
    }

    @Override
    public boolean makesOpenTrapdoorAboveClimbable(BlockState state, IWorldReader world, BlockPos pos, BlockState trapdoorState) {
        return state.getValue(COUNT) >= 32;
    }


}
